var sys = require('sys');
var spawn = require('child_process').spawn;
var fs = require("fs");
var startByte = 0;
var filename = process.ARGV[2];
var index;

if (!filename)
  return sys.puts("Usage: node <server.js> <filename>");

/*
var tail = spawn("tail", ["-f", filename]);
tail.stdout.on("data", function (data) {
    index = data;
});*/


  fs.stat(filename, function(err, stats){
	  if (err) throw err;
	  startByte = stats.size;
	  sys.puts(startByte);
  });

  fs.watchFile(filename, function (curr, prev) {
	  fs.stat(filename, function(err, stats){
	    if (err) throw err;
	    fs.createReadStream(filename, {
	      start: startByte,
	      end: stats.size
	    }).addListener("data", function(lines) {
	      //sys.puts(lines);
              //res.end(lines);
              index = lines;
	      startByte = stats.size;
	    });
	  });
	});



http = require('http');
http.createServer(function (req, res) {
  sys.puts("new connection..");
  //res.writeHead(200, {'Content-Type': "text/plain;charset=UTF-8"});
  res.writeHead(200, {'Content-Type': "text/html"});
  res.end(index);
  /*
  tail.stdout.on("data", function (data) {
    res.end(data);
  });
 
  tail.stdout.on("data", function (data) {
  	console.log(data);
  });*/

  
   res.end("+++++++++");

  //res.end("++");
}).listen(3000);

/*
fs.watchFile(filename, function (curr, prev) {
	  fs.stat(filename, function(err, stats){
	    if (err) throw err;
	    fs.createReadStream(filename, {
	      start: startByte,
	      end: stats.size
	    }).addListener("data", function(lines) {
	      sys.puts(lines);
	      startByte = stats.size;
	    });
	  });
	});
*/

